﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;

namespace PdfCompiler
{
    public class PdfHelper
    {
        
        public static string GetSha1FromFile(string filepath)
        {
            string strResult = "";
            string strHashData = "";

            byte[] arrbytHashValue;
            System.IO.FileStream oFileStream = null;

            System.Security.Cryptography.SHA1CryptoServiceProvider oSHA1Hasher =
                       new System.Security.Cryptography.SHA1CryptoServiceProvider();

            try
            {
                oFileStream = GetFileStream(filepath);
                arrbytHashValue = oSHA1Hasher.ComputeHash(oFileStream);
                oFileStream.Close();

                strHashData = System.BitConverter.ToString(arrbytHashValue);
                strHashData = strHashData.Replace("-", "");
                strResult = strHashData;
            }
            catch (System.Exception ex)
            {
                throw new Exception("Error generating hash from file " + filepath, ex);
            }

            return (strResult);
        }

        public static string GetSha1FromString(string text)
        {
            string strResult = "";
            string strHashData = "";

            byte[] arrbytHashValue;
            byte[] arrbytText;

            System.Security.Cryptography.SHA1CryptoServiceProvider oSHA1Hasher =
                       new System.Security.Cryptography.SHA1CryptoServiceProvider();

            try
            {
                arrbytText = ConvertStringToByteArray(text);
                
                arrbytHashValue = oSHA1Hasher.ComputeHash(arrbytText);

                strHashData = System.BitConverter.ToString(arrbytHashValue);
                strHashData = strHashData.Replace("-", "");
                strResult = strHashData;
            }
            catch (System.Exception ex)
            {
                throw new Exception("Error generating hash from string", ex);
            }

            return (strResult);
        }

        public static byte[] ConvertStringToByteArray(string data)
        {
            return (new System.Text.UnicodeEncoding()).GetBytes(data);
        }

        public static System.IO.FileStream GetFileStream(string pathName)
        {
            return (new System.IO.FileStream(pathName, System.IO.FileMode.Open,
                      System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite));
        }

        public static void ConcatenatePdfFiles(string[] filepaths, string outputFilepath)
        {
            try
            {
                if (File.Exists(outputFilepath))
                    File.Delete(outputFilepath);

                PdfDocument[] documents = new PdfDocument[filepaths.Length];

                // Open the input files
                for (int i = 0; i < filepaths.Length; i++)
                    documents[i] = PdfReader.Open(filepaths[i], PdfDocumentOpenMode.Import);

                // Create the output document
                PdfDocument outputDocument = new PdfDocument();

                // Get pages from the document and add them to the output document
                for (int i = 0; i < filepaths.Length; i++)
                {
                    foreach (PdfPage page in documents[i].Pages)
                        outputDocument.AddPage(page);
                }

                // Save the document...
                string filename = outputFilepath;
                outputDocument.Save(filename);
            }
            catch (Exception ex)
            {
                throw new Exception("Error concatenando archivos pdf", ex);
            }
        }

        public static void ConcatenatePdfPages(List<PdfPageNumber> pages, string outputFilepath)
        {
            try
            {
                if (File.Exists(outputFilepath))
                    File.Delete(outputFilepath);

                string[] filepaths = pages.Select(p => p.FileName).Distinct().ToArray();

                Dictionary<string, PdfDocument> documents = new Dictionary<string, PdfDocument>();

                // Open the input files
                foreach (var path in filepaths)
                    documents.Add(path, PdfReader.Open(path, PdfDocumentOpenMode.Import));

                // Create the output document
                PdfDocument outputDocument = new PdfDocument();

                // Get pages from the document and add them to the output document
                foreach (var p in pages)
                {
                    PdfPage page = documents[p.FileName].Pages[p.Page - 1];
                    outputDocument.AddPage(page);
                }

                // Save the document...
                string filename = outputFilepath;
                outputDocument.Save(filename);
            }
            catch (Exception ex)
            {
                throw new Exception("Error concatenando archivos pdf", ex);
            }
        }

    }

    public class PdfPageNumber
    {
        public string FileName { get; set; }
        public int Page { get; set; }
    }

}
